package ecom.shell;

import java.io.PrintStream;
import java.util.StringTokenizer;

import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;

import ecom.beans.EcomAdminBean;
import ecom.beans.EcomAdminRemote;

import shell.ShellCommand;
import shell.ShellContext;


public class CreateAccountCommand implements ShellCommand {
	private ShellContext _context = null;
	private EcomAdminRemote adminRemote;
	
	public CreateAccountCommand(ShellContext context) {
		System.setProperty(Context.INITIAL_CONTEXT_FACTORY, "org.objectweb.carol.jndi.spi.MultiOrbInitialContextFactory");

		try {
			Context initialContext = new InitialContext();
			Object o = initialContext.lookup(EcomAdminBean.class.getName()+"_"+EcomAdminRemote.class.getName()+"@remote");
			System.out.println(o.toString());
			if (o instanceof EcomAdminRemote) {
	            adminRemote = (EcomAdminRemote) o;
	        }
			
		} catch (NamingException e) {
			// TODO Auto-generated catch block
			System.out.println("ERREUR");
			e.printStackTrace();
		}
		
		_context = context;
		
	}

	public String getName() {
		return "createAccount";
	}

	public String getUsage() {
		return "createAccount <AccountId> <AccountName> <AccountBalance>";
	}

	public String getShortDescription() {
		return "Creates and initalizes a new account";
	}

	public void execute(String s, PrintStream out, PrintStream err) {
		StringTokenizer st = new StringTokenizer(s, " ");
		// Ignore the command name.
		st.nextToken();

		// There should be three string.
		if (st.countTokens() == 2) {
			/*int id = Integer.parseInt(st.nextToken());
			int ownerId = Integer.parseInt(st.nextToken());*/
			String email = st.nextToken();
			double bal = Double.parseDouble(st.nextToken());
			
			out.println("Name = "+email);
			
			adminRemote.createAccount(email, bal);
			out.println("Account successfully created");
		}
		
		else {
			err.println(this.getUsage());
		}
	}
}
